require 'net/http'
require 'fileutils'

class PuushDownloader
  MAX_RETRIES = 5
  
  def self.download_file(id, subfolder, logger, retries=0)
    logger.error "Too many retries, this file doesn't seem to exist." and return false if retries > MAX_RETRIES 
    begin
      Net::HTTP.start("puu.sh") do |http|
        http.request_get('/' + URI.encode(id)) do |response|
          filename = PuushHelper.get_file_name_from_response(response)
          return false if !filename
        
          filename = id + " - " + filename
          path = subfolder + "/" + filename
        
          return filename if File.exists?(path)
        
          FileUtils.mkdir_p(subfolder)
          FileUtils.touch(path)
        
          file = open path, 'wb'
        
          response.read_body do |segment|
            file.write(segment)
          end
        
          return filename
        end
      end
    rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError, Errno::EHOSTUNREACH, SocketError,
      Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => e
      
      logger.warn "Connection error, retrying (#{retries})...: " + e.to_s
      self.download_file(id, subfolder, logger, retries+1)
      #return false
    end
  end
end